package com.vrv.vap.baseline.controller;

import com.vrv.vap.baseline.service.impl.UserDataAuthExportService;
import com.vrv.vap.baseline.service.impl.UserDataAuthImportService;
import com.vrv.vap.baseline.util.FileOperationUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/api/user_data_auth")
public class UserDataAuthController {
    private static final Logger log = LoggerFactory.getLogger(UserDataAuthController.class);
    private final UserDataAuthExportService userDataAuthExportService;
    private final UserDataAuthImportService userDataAuthImportService;
    private final FileOperationUtil fileOperationUtil;
    
    public UserDataAuthController(UserDataAuthExportService userDataAuthExportService,
                                UserDataAuthImportService userDataAuthImportService,
                                FileOperationUtil fileOperationUtil) {
        this.userDataAuthExportService = userDataAuthExportService;
        this.userDataAuthImportService = userDataAuthImportService;
        this.fileOperationUtil = fileOperationUtil;
    }
    
    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response) throws IOException {
        try {
            String zipFilePath = userDataAuthExportService.exportZip();
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=user_data_auth.zip");
            fileOperationUtil.writeFileToResponse(zipFilePath, response);
        } catch (Exception e) {
            log.error("导出数据失败", e);
            throw new RuntimeException("导出数据失败", e);
        }
    }
    
    @PostMapping("/import")
    public ResponseEntity<String> importData(@RequestParam("file") MultipartFile file) {
        try {
            // 验证文件类型
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body("请选择要上传的文件");
            }
            
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || !originalFilename.endsWith(".zip")) {
                return ResponseEntity.badRequest().body("只支持上传ZIP格式的文件");
            }
            
            // 调用导入服务处理ZIP文件
            int importedCount = userDataAuthImportService.importFromZip(file);
            
            return ResponseEntity.ok("成功导入" + importedCount + "条记录");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("导入失败: " + e.getMessage());
        }
    }
}